<template>
  <div class="main_box" style="padding:10px;">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{$route.query.id?"修 改 康 来 项 目 组 信 息":"新 增 康 来 项 目 组"}}</h2>
        <el-button
          type="success"
          plain
          size="small"
          icon="fa fa-mail-forward"
          @click="returnList"
        >
          返 回</el-button
        >
      </div>
      <el-form
        :model="addForm"
        ref="addForm"
        label-width="200px"
        :rules="roleRules"
      >
        <el-row>
          <el-form-item label="项目组名称" prop="itemName">
            <el-input
              v-model="addForm.itemName"
              clearable
              @blur="checkItemNameIsExist"
            ></el-input>
            <br /><span
              id="insNameHides"
              :hidden="insNameHide"
              style="color: red; font-size: xx-small;"
            >
              <i class="el-icon-warning" />项目名称重复！</span
            >
          </el-form-item>
          <el-form-item label="项目组别称" prop="ItemShortName">
            <el-input v-model="addForm.itemShortName" clearable></el-input>
          </el-form-item>
          <el-form-item label="检测时长" prop="itemTime">
            <el-input v-model="addForm.itemTime" clearable></el-input>
          </el-form-item>
          <el-form-item label="收费价格" prop="itemPrice">
            <el-input type="number" v-model="addForm.itemPrice"></el-input>
          </el-form-item>

          <el-form-item label="收费级别">
            <el-select v-model="addForm.feeLevels" placeholder="请选择收费级别" clearable filterable multiple @change="getTable">
              <el-option v-for="item in feeLevelList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方法学">
            <template slot-scope="{row}">
              <el-select v-model="addForm.methodologys" placeholder="请选择方法学" clearable filterable multiple @change="getTable">
                <el-option v-for="item in methodologyList" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="地区" style="width:100%;">
            <Address  :level="2" :addressList="addForm.addressList" style="width:100%"
            @getAddress="getAddress"  :isCheckStrictly="true" :multiple="true"></Address>
          </el-form-item>
          <el-table :data="addForm.baseItemPrices" style="margin-bottom: 10px;" v-if="addForm.baseItemPrices.length">
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="{row,$index}">
                <el-button type="danger" circle icon="el-icon-minus" @click="addForm.baseItemPrices.splice($index,1)"></el-button>
              </template>
            </el-table-column>
            <el-table-column label="地址" width="200" align="center">
              <template slot-scope="{row:{provinceName,cityName}}">
                <div>
                  {{ provinceName?(provinceName+(cityName?cityName:'')):'' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="feeLevel" label="收费级别" width="180" align="center">

            </el-table-column>
            <el-table-column prop="methodology" label="方法学" width="180" align="center">

            </el-table-column>
            <el-table-column prop="itemPrice" label="价格" align="center">
                <template slot-scope="{row}">
                  <el-input v-maxnum="{obj:row,key:'itemPrice',length:2,zero:true}" v-model="row.itemPrice"></el-input>
                </template>
            </el-table-column>
          </el-table>
          <el-col :span="24">
            <el-form-item label="关联康来(子)项目" prop="subItemIdList" style="width:100%;">
            <el-select multiple v-model="addForm.subItemIdList" style="width:100%;" placeholder="请选择康来子项目">
               <el-option
              v-for="item in pickSubItemIdList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
            </el-select>
          </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item
              label="检测流程"
              prop="itemProcess"
              style="width:100%;"
            >
              <el-input
                type="textarea"
                autosize
                v-model="addForm.itemProcess"
                placeholder="请输入检测流程"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="临床意义"
              prop="itemMeaning"
              style="width:100%;"
            >
              <el-input
                type="textarea"
                autosize
                v-model="addForm.itemMeaning"
                 placeholder="请输入临床意义"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="注意事项" prop="itemNote" style="width:100%;">
              <el-input
                type="textarea"
                autosize
                v-model="addForm.itemNote"
                placeholder="请输入注意事项"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" style="width:100%;">
              <el-input
                type="textarea"
                autosize
                v-model="addForm.remark"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button
              type="primary"
              @click="sureClick"
              :disabled="sureDisabled"
              >保 存</el-button
            >
            <el-button @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import ReportItemApi from "@/api/report/reportItem";
import Address from "../../components/Address.vue";
export default {
  data() {
    return {
      addForm: {
        itemId: "",
        itemName: "",
        itemShortName: "",
        itemTime: "",
        itemPrice: "",
        itemProcess: "",
        itemMeaning: "",
        itemNote: "",
        subItemIdList:[],
        remark:"",
        addressList:[],
        methodologys:[],
        feeLevels:[],
        baseItemPrices:[],
      },
      pickSubItemIdList:[],
      methodologyList:[
        {id:"化学发光学",name:"化学发光学"},
        {id:"胶体金法",name:"胶体金法"},
        {id:"其它",name:"其它"}
      ],
      feeLevelList:[
        {id:"一类",name:"一类"},
        {id:"二类",name:"二类"},
        {id:"三类",name:"三类"},
      ],
      sureDisabled: false,
      roleRules: {
        itemName: [
          {
            required: true,
            message: "请输入项目名称",
            trigger: "blur"
          }
        ]
      },
      insNameHide: true // 项目名称重复警告
    };
  },
  components:{
    Address
  },
  mounted() {
    this.init();
    // setInterval(()=>{
    //   this.a = this.a==15?13:15
    //   this.addForm.addressList = [[13]]
    // },4000)
  },
  methods: {
    init() {
      if (this.$route.query.id) {
        this.addForm.itemId = this.$route.query.itemId;
      }
      this.getData();
    },
    getAddress({list}) {
      this.addForm.addressList = list.map(item=>[item.provinceId,item.cityId,item.provinceName,item.cityName]);
      this.getTable()
    },
    addressToObj(addressList){
      const arr = []
      const ids = addressList.map(item=>item.filter(item2=>typeof item2==='number'))
      const names = addressList.map(item=>item.filter(item2=>typeof item2==='string'&&item2))
      addressList.forEach((_,index)=>{
        arr.push({
          provinceId:ids[index][0],
          provinceName:names[index][0],
          cityId:ids[index][1]||'',
          cityName:names[index][1]||''
        })
      })
      return arr
    },
    checkItemNameIsExist() {
      // 项目名称重复校验
      let _this = this;
      if (_this.addForm.itemName !== "" && _this.addForm.itemName !== null) {
        _this.insNameHide = true;
        let cond = {
          itemName: _this.addForm.itemName
        };
        ReportItemApi.inExisrReportSubItems(cond).then(res => {
          // 检验条件
          // console.log(res.data)
          if (res.data.code == 1) {
            this.insNameHide = false; // 满足条件 取消隐藏
            this.sureDisabled = true;
          } else {
            this.insNameHide = true; // 不重名，隐藏提示
            this.sureDisabled = false;
          }
        });
      }
    },
    getData() {
      let _this = this;
      this.listReportSubItem()
      if(!this.$route.query.id){
        return
      }
      ReportItemApi.getReportItem({ itemId: _this.$route.query.id }).then(
        res => {
          this.formatData(res.data)
          this.$Utils.bindingBean(this.addForm, res.data);

          console.log(this.addForm.baseItemPrices)
          this.addForm.subItemIdList = res.data.subItemVos.map(res=>res.subItemId)
        }
      );

    },
    // 处理数据为页面所需要的
    formatData(data){
      const {baseItemPrices} = data
      const addressList = []
      const methodologys =[]
      const feeLevels =[]
      baseItemPrices.forEach(item=>{

        if(!addressList.some(item2=>{
          return item2.join("")===item.provinceId+(item.cityId||'')+item.provinceName+(item.cityName||'')
        })){
          addressList.push([item.provinceId,item.cityId||"",item.provinceName,item.cityName||""])
        }
        if(!methodologys.some(item2=>item2==item.methodology))methodologys.push(item.methodology)
        if(!feeLevels.some(item2=>item2==item.feeLevel))feeLevels.push(item.feeLevel)
        // this.$set(item,"methodologyName",this.methodologyList.find(item2=>item2.id==item.methodology).name)
        // this.$set(item,"feeLevelName",this.feeLevelList.find(item2=>item2.id==item.feeLevel).name)
      })
      data.addressList = addressList
      data.methodologys = methodologys
      data.feeLevels = feeLevels
    },
    getTable(){
      let {methodologys,feeLevels,addressList,baseItemPrices} = this.addForm
      if(!methodologys.length||!feeLevels.length||!addressList.length){
          return this.addForm.baseItemPrices = []
      }
      let newtable = this.generateTable([this.addressToObj(addressList),feeLevels,methodologys])
      // console.log(JSON.parse(JSON.stringify(newtable)))
      newtable = newtable.map(item=>({
        ...item[0],
        feeLevel:item[1],
        methodology:item[2],
        itemPrice:""
      }))

      // 比较新旧来把价格赋值
      newtable.forEach(item=>{
        const target = baseItemPrices.find(item2=>item2.provinceId==item.provinceId&&(item2.cityId||'')==item.cityId&&item2.feeLevel==item.feeLevel&&item2.methodology==item.methodology)
        if(target)item.itemPrice = target.itemPrice
      })
      this.addForm.baseItemPrices = newtable
    },

    // 收费级别、方法学、地区三者变化就重新生成表格
    generateTable(arr, table = [], obj = [], i = 0,isArr = true){
        if(!isArr&&obj.length===0)obj = {}
        arr[i].forEach(item => {
            let temp = isArr?[...obj, item]:{...obj,...item}
            if (i === arr.length - 1) {
                table.push(temp)
            } else {
                this.generateTable(arr, table, temp, i + 1)
            }
        })
        return table
    },
    checkData(){
      const {baseItemPrices} = this.addForm
      // for(let i=0;i<baseItemPrices.length;i++){
      //   if(baseItemPrices[i].itemPrice===""){
      //     this.$message.error(`第${i+1}行请输入价格`)
      //     return false
      //   }
      // }
      this.baseItemPrices = baseItemPrices.map(item=>{
        const val = {...item}
        // delete val.methodologyName
        // delete val.feeLevelName
        return val
      })
      return true
    },
    sureClick() {
      let _this = this;
      _this.$refs.addForm.validate(valid => {
        if (valid) {
          if(!this.checkData()) return

          if (this.addForm.itemId) {
            //做一个基础的判断，id不为空就编辑，id为空就增加
            this.$confirm(
              message.MSG_CONFIRM_SAVE_ALTER,
              message.TITLE_PROMPT,
              {}
            ).then(() => {
              this.editData();
            });
          } else {
            this.$confirm(
              message.MSG_CONFIRM_SAVE_ADD,
              message.TITLE_PROMPT,
              {}
            ).then(() => {
              this.addData();
            });
          }
        }
      });
    },
    addData() {
      let _this = this;
      let cond = {
        itemName: _this.addForm.itemName,
        itemTime: _this.addForm.itemTime,
        itemShortName: _this.addForm.itemShortName,
        itemPrice: _this.addForm.itemPrice,
        itemProcess: _this.addForm.itemProcess,
        itemMeaning: _this.addForm.itemMeaning,
        itemNote: _this.addForm.itemNote,
        subItemIdList:_this.addForm.subItemIdList,
        baseItemPrices: this.baseItemPrices,
        remark:_this.addForm.remark
      };
      ReportItemApi.addReportItem(cond).then(data => {
        this.$notify.success({
          title: message.TITLE_SUCCESS,
          message: message.MSG_ACTION_SUCCESS
        });
        this.returnList();
      });
    },
    editData() {
      let _this = this;
      let cond = {
        itemId: _this.addForm.itemId,
        itemName: _this.addForm.itemName,
        itemShortName: _this.addForm.itemShortName,
        itemTime: _this.addForm.itemTime,
        itemPrice: _this.addForm.itemPrice,
        itemProcess: _this.addForm.itemProcess,
        itemMeaning: _this.addForm.itemMeaning,
        itemNote: _this.addForm.itemNote,
        subItemIdList:_this.addForm.subItemIdList,
        baseItemPrices: this.baseItemPrices,
        remark:_this.addForm.remark
      };

      ReportItemApi.editReportItem(cond).then(data => {
        this.$notify.success({
          title: message.TITLE_SUCCESS,
          message: message.MSG_ACTION_SUCCESS
        })
        this.returnList();
      }).catch(err=>{
        this.$confirm('该项目与医院组合项目存在关联, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          cond.update = 1
          ReportItemApi.editReportItem(cond).then(data => {
              this.$notify.success({
                title: message.TITLE_SUCCESS,
                message: message.MSG_ACTION_SUCCESS
              })
              this.returnList();
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      });
    },
    listReportSubItem() {
      // 获取报告单子项目列表
      let _this = this;
      _this.loadingIns = true;
      ReportItemApi.listReportSubItems().then(res => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.pickSubItemIdList = res.data.map(item => {
            return {
              value: item.subItemId,
              label: item.subItemName
            };
          });
        }, 200);
      });
    },
    returnList() {
      // this.$router.go(-1)
      this.$store.dispatch("delView", this.$route);
      this.$router.push({ path: "/items/reportItemManagement" });
    }
  }
};
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
<style scoped>
.add_wrap {
  padding-top: 10px;
  padding-left: 23px;
}
</style>
